#include "CChar.h"
#include "CSemaphore.h"
#include "CGuildShopHandler.h"
#include "CGuildShop.h"
#include "CGuildBuyMenuPacket.h"

CGuildBuyMenuPacket::CGuildBuyMenuPacket(unsigned short guildID, CChar * schar) {
	unsigned char packetCount = 0;
	unsigned char itemCount = 0;
	createPacket();
	CGuildShop * guildShop = NULL;
	CGuildShopHandler::waitGuildShopList();
	guildShop = CGuildShopHandler::getGuildShop(guildID);
	if (guildShop != NULL) {
		for(unsigned char slotID = 1; slotID <= guildShop->getSize(); slotID++) {
			CItem * item = NULL;
			item = guildShop->getItem(slotID);
			if(item != NULL) {
				if(guildShop->itemIsInBuyMenu(item->getId())) {
					unsigned short itemID = item->getId();
					unsigned char quantity = (unsigned char)item->getQuantity();
					unsigned char max = item->getStackSize();
					unsigned long price = guildShop->getPrice(itemID);

					memcpy(data+(0x08 * itemCount)+0x04-0x04, &itemID, 2);
					data[(0x08 * itemCount)+0x06-0x04] = quantity;
					data[(0x08 * itemCount)+0x07-0x04] = max;
					memcpy(data+(0x08 * itemCount)+0x08-0x04, &price, 4);

					itemCount++;
					data[0xF4-0x04] = itemCount;
				}
			}
			// Max 30 items per packet
			if( (itemCount == 30) && (itemCount < guildShop->getSize()) ) {
				// 0x40 = first packet
				if(packetCount == 0)
					data[0xF5-0x04] = 0x40;
				else
					data[0xF5-0x04] = packetCount;

				// Limit of 3 packets of items for Buy menu
				if(packetCount == 2) {
					data[0xF5-0x04] += 0x80;
					CGuildShopHandler::exitGuildShopList();
					return;
				}
				
				// Send the packet
				schar->quePacket(*this);

				// Reset the packet
				itemCount = 0;
				createPacket();

				packetCount++;
			}
		}
	}
	if(itemCount > 0) {
		data[0xF4-0x04] = itemCount;

		// 0x80 = last packet
		data[0xF5-0x04] += (0x80 + packetCount);

	}
	CGuildShopHandler::exitGuildShopList();
}

CGuildBuyMenuPacket::~CGuildBuyMenuPacket() {
}

void CGuildBuyMenuPacket::createPacket() {
	this->type		=	0x83;
	this->size		=	0x7C;

	memset(this->data, 0, sizeof(data));
}
